package protocol;

import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

/**
 * @author radu
 */
public abstract class Message {

    public abstract Executor getServerExecutor();

    public static Message ParseMessageServer(String strMessage) throws Exception {
        //Parsing the xml input
        Document doc;
        Element root;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();


        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(strMessage));
        doc = db.parse(is);

        root = doc.getDocumentElement();
        root.normalize();

        //extract the command name
        String commandName = root.getTagName();
        switch (commandName) {
            case "connect":
                return new MessageConnectReq(root);
            case "start":
                return new MessageStartReq(root);
            case "stop":
                return new MessageStopReq(root);
            case "create":
                return new MessageCreatePollReq(root);
            case "error":
                return new MessageCreatePollRep(root);
            case "pause":
                return new MessagePauseReq(root);
            case "resume":
                return new MessageResumeReq(root);
            default:
                throw new Exception("message type not accepted");
        }
    }

    public static Message ParseMessageClient(String strMessage) throws Exception {
        //Parsing the xml input
        Document doc;
        Element root;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();


        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(strMessage));
        doc = db.parse(is);

        root = doc.getDocumentElement();
        root.normalize();

        //extract the command name
        String commandName = root.getTagName();
        switch (commandName) {
            case "connected":
                return new MessageConnectRep(root);
            case "started":
                return new MessageStartRep(root);
            case "stopped":
                return new MessageStopRep(root);
            case "created":
                return new MessageCreatePollRep(root);
            case "error":
                return new MessageCreatePollRep(root);
            case "paused":
                return new MessagePauseRep(root);
            case "resumed":
                return new MessageResumeRep(root);
            default:
                throw new Exception("message type not accepted");
        }

    }
}
